<?php
require_once APP . '/application/admincontrollers/AdminAction.php';
/**
 * 后台管理主页
 * @package admin
 */
class MeetController extends AdminAction
{
    
	/**
	 * Enter description here...
	 *
	 * @var MeetingModel
	 */
	private $meet;
    public function init()
    {
    	require_once(APP . '/application/models/MeetingModel.php');
    	
        $this->meet = new MeetingModel($this->db);
    }


    /**
     * 加载框架页
     */
    public function addAction()
    {
        //加载默认视图
    }
    
    public function doaddAction()
    {
    	$params = $this->getAllParams();
    	
    	$this->meet->add($params);
    	
    	$this->view->msg = '添加成功';
    	$this->view->url = $this->url($this->view->baseUrl, "meet", "add", "", "admin");
    	$this->showmessage();
    }
    
    public function listAction()
    {
    	$nowp = (int) $this->getParam("nowp", 1);
    	$per_page = 20;
    	
    	$result = $this->meet->fetchAll($nowp, $per_page);
    	
    	$this->view->nowp = $nowp;
        $this->view->list = $result['list'];
        $this->view->page = $result['page'];
    }
    
    
    public function delAction()
    {
    	$mid = (int) $this->getParam("mid");
    	$nowp = (int) $this->getParam("nowp");
    	
    	$this->meet->del($mid);
    	
    	header("location:" . $this->url($this->view->baseUrl, "meet", "list", "nowp=" . $nowp, "admin"));
    }
    
    
    public function editAction()
    {
    	$mid = (int) $this->getParam("mid");
    	$nowp = (int) $this->getParam("nowp");
    	
        $this->view->nowp = $nowp;
        $this->view->content = $this->meet->show($mid);
    }
    
    public function doeditAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$nowp = (int)$this->getParam("nowp");
    	$params = $this->getAllParams();
    	
    	$nowp = $this->getParam("nowp");
    	
    	$this->meet->change($mid, $params);
    	
    	$this->view->msg = '编辑成功';
    	$this->view->url = $this->url($this->view->baseUrl, "meet", "list", "nowp=" . $nowp . '&group=' . $oldgroup, "admin");
    	$this->showmessage();
    }
    
    public function showAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$this->view->content = $this->meet->show($mid);
    }
    
    public function dictAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$onowp = $this->getParam("onowp");
    	$nowp = $this->getParam("nowp");
    	
    	require_once(APP . '/application/models/DictModel.php');
    	
        $obj_dict = new DictModel($this->db);
    	
    	$arr_dict = $this->db->fetchAll("select did from mdlist where mid=?", array($mid));
    	$arr_dict_dids = array();
    	foreach ($arr_dict as $v){
    		$arr_dict_dids[$v['did']] = $v['did'];
    	}
    	$arr_all_dict = $obj_dict->fetchAll($nowp, 15);
    	
    	$this->view->mid = $mid;
    	$this->view->onowp = $onowp;
    	$this->view->dict = $arr_dict_dids;
    	$this->view->all_dict = $arr_all_dict['list'];
    	$this->view->page = $arr_all_dict['page'];
    }
    
    /**
     * ajax 
     *
     */
    public function dictsetAction()
    {
    	$this->setAutoRender(false);
    	
    	$mid = (int)$this->getParam("mid");
    	$did = (int) $this->getParam("did");
    	$check = (int)$this->getParam("check");
    	
    	$seq = $this->db->fetchOne("select seq from dict where did=?", array($did));
    	
    	if ($check){
    		$this->db->insert("mdlist", array("mid" => $mid, "did" => $did, 'seq' => $seq));
    	}else{
    		$this->db->delete("mdlist", "mid=" . $mid . ' and did=' . $did);
    	}
    }
    
    public function dictchangeAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$onowp = $this->getParam("onowp");
    	
    	$this->view->mid = $mid;
    	$this->view->onowp = $onowp;
    	$this->view->dict = $this->meet->fetchAllDict($mid);
    }
    
    public function seqchangeAction()
    {
    	$this->setAutoRender(false);
    	
    	$mid = (int)$this->getParam("mid");
    	$did = (int) $this->getParam("did");
    	$seq = (int)$this->getParam("seq");
    	
    	$this->db->update("mdlist", array("seq" => $seq), "mid=" . $mid . ' and did=' . $did);
    }
    
    public function addmailAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$onowp = $this->getParam("onowp");
    	$u_content = $this->getParam("content", "");
    	// $u_content = urlencode(base64_encode(gzcompress($content, 9)));
    	$content = @gzuncompress(base64_decode($u_content));
    	
    	$this->view->mid = $mid;
    	$this->view->onowp = $onowp;
    	$this->view->content = $content;
    }
    
    public function doaddmailAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$onowp = (int)$this->getParam("onowp");
    	$content = $this->getParam("content");
    	$arr_tmp_mails = split("\n", $content);
    	
    	$arr_mails = array();
    	foreach ($arr_tmp_mails as $v){
    		$mail = trim($v);
    		if (empty($mail))
    			continue;
    		
    		if (!ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+",$mail)){
    			$u_content = urlencode(base64_encode(gzcompress($content, 9)));
    			$this->view->msg = "邮箱格式不正确！ - 《" . $mail . '》';
		    	$this->view->url = $this->url($this->view->baseUrl, "meet", "addmail", "nowp=" . $onowp .'&mid=' . $mid .'&content=' .$u_content, "admin");
		    	$this->showmessage();
    		}
    		
    		$arr_mails[] = $mail;
    	}
    	
    	// 读取目前的邮件列表 防止目前的邮件列表重复
    	$_arr_exists = $this->db->fetchAll("select email from email where mid=?", array($mid));
    	$arr_exists = array();
    	foreach ($_arr_exists as $v){
    		$arr_exists[$v['email']] = $v['email'];
    	}
    	foreach ($arr_mails as $key => $v){
    		if (isset($arr_exists[$v])){
    			unset($arr_mails[$key]);
    		}
    		$arr_exists[$v] = $v;
    	}
    	
    	if (empty($arr_mails)){
    		$this->view->msg = "没有要插入的邮件地址！";
    		$u_content = urlencode(base64_encode(gzcompress($content, 9)));
		    $this->view->url = $this->url($this->view->baseUrl, "meet", "addmail", "nowp=" . $onowp .'&mid=' . $mid .'&content=' . $u_content, "admin");
		    $this->showmessage();
    	}
    	// 构造语句进行插入
    	$sql_pre = "insert into `email`(mid,`email`,`code`) values";
    	$sql_val = '';
    	$comma = "";
    	$uniqid = uniqid();
    	$i = 0;
    	foreach ($arr_mails as $mail){
    		$mail = mysql_escape_string($mail);
    		$code = substr(md5($mail . $uniqid), 10, 20);
    		$sql_val .= $comma . "({$mid},'{$mail}','{$code}')";
    		$comma = ',';
    		$i++;
    		
    		if ($i % 300 == 0){// 每300个为一个批次
    			$this->db->query($sql_pre . $sql_val);
    			$sql_val = '';
    			$comma = '';
    		}
    	}
    	
    	if (!empty($sql_val)){
    		$this->db->query($sql_pre . $sql_val);
    	}
    	    	
    	$this->view->msg = '添加成功';
    	$this->view->url = $this->url($this->view->baseUrl, "meet", "list", "nowp=" . $onowp, "admin");
    	$this->showmessage();
    }
    
    public function maillistAction()
    {
    	$mid = (int)$this->getParam("mid");
    	$onowp = (int)$this->getParam("onowp");
    	
    	$arr_mail = $this->db->fetchAll("select * from email where mid=?", array($mid));
    	$templates = $this->db->fetchAll("select * from template order by seq desc, tid desc");
    	
    	$this->view->mid = $mid;
    	$this->view->onowp = $onowp;
    	$this->view->list = $arr_mail;
    	$this->view->templates = $templates;
    }
    
	/**
     * 发送邮件
     *
     */
    public function sendAction()
    {
    	set_time_limit(0);
    	$this->setAutoRender(false);
    	
    	$stype = $this->getParam("stype", "");// all, select
    	$eids = $this->getParam("eids");
    	$tid = (int)$this->getParam("tid");
    	$mid = (int)$this->getParam("mid");
    	
    	$str_ids = "";
    	if ($stype == 'all' || $stype == 'select')
    	{
	    	if (is_array($eids) && count($eids) > 0)
	    		$str_ids = implode(",", $eids);
    	}
		
    	$this->meet->sendMail($mid, $tid, $stype, $str_ids, $this->view->fullUrl);
    }
    
    /**
     * 导出excel
     *
     */
    public function excelAction()
    {
    	$this->setAutoRender(false);
    	set_time_limit(0);
    	ini_set('memory_limit', '1024M');
    	
    	$outputFileName = 'out.xls';
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header('Content-Disposition:inline;filename="'.$outputFileName.'"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: no-cache");
		ob_flush();
		
    	$mid = (int)$this->getParam("mid");
    	
    	$arr_meet = $this->meet->show($mid);
    	$arr_dict = $this->meet->fetchAllDict($mid);
    	$arr_user = $this->db->fetchAll("select * from user where mid=?", array($mid));
    	
    	$path = APP . '/application/models/pear';
    	set_include_path(get_include_path() . PATH_SEPARATOR . $path);
    	require 'Spreadsheet/Excel/Writer.php';

		$workbook = new Spreadsheet_Excel_Writer(APP . '/cache/out.xls');
		$workbook->setVersion(8);
		$worksheet = $workbook->addWorksheet();
		$worksheet->setInputEncoding("utf-8");

		$format_bold = $workbook->addFormat();
		//设置为样试为粗体
		$format_bold->setBold();

		//设置单元格内容
		$rowwidth = array();
		
		// 设置表头
		$worksheet->writeString(0, 0, "邮件地址", $format_bold);
		$worksheet->writeString(1, 0, "EMAIL", $format_bold);
		$rowwidth[0] = strlen('邮件地址');
		
		$worksheet->writeString(0, 1, "注册时间", $format_bold);
		$worksheet->writeString(1, 1, "RETTIME", $format_bold);
		$rowwidth[1] = strlen('注册时间');
		
		$worksheet->writeString(0, 2, "注册IP", $format_bold);
		$worksheet->writeString(1, 2, "REGIP", $format_bold);
		$rowwidth[2] = strlen('注册IP');
		
		$i = 3;
		foreach ($arr_dict as $v){
			$worksheet->writeString(0, $i, $v['key'], $format_bold);
			$worksheet->writeString(1, $i, $v['enkey'], $format_bold);
			$rowwidth[$i] = max(strlen($v['key']), strlen($v['enkey']));
			$i++;
		}
		
		// 设置数据
		$row = 2;
		foreach ($arr_user as $user){
			$worksheet->writeString($row, 0, $user['email']);
			$worksheet->writeString($row, 1, $user['regtime']);
			$worksheet->writeString($row, 2, long2ip($user['regip']));
			
			$rowwidth[0] = max($rowwidth[0], strlen($user['email']));
			$rowwidth[1] = max($rowwidth[1], strlen($user['regtime']));
			$rowwidth[2] = max($rowwidth[2], strlen($user['regip']));
			
			$content = unserialize($user['content']);
			$i = 3;
			foreach ($arr_dict as $v){
				$value = $content[$v['did']];
				$rowwidth[$i] = max($rowwidth[$i], strlen($value));
				$worksheet->writeString($row, $i, $value);
				$i++;
			}
			
			$row++;
		}
		
		// 设置宽度
		foreach ($rowwidth as $index => $len){
			$value = min($len * 1.2, 30);
			$value = max(10, $value);
			$worksheet->setColumn($index, $index, $value);
		}
		
		$workbook->close();
		readfile(APP . '/cache/out.xls');
		unlink(APP . '/cache/out.xls');
    }
}